﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Pop3Client;
using Kiiro.ExceptionManagement;

namespace Kiiro.Model
{
    public class EmailModel
    {
        #region Singleton

        private static EmailModel instance = null;
        private static readonly object threadLock = new object ( );

        private EmailModel ( )
        {
        }

        public static EmailModel Instance
        {
            get
            {
                lock ( threadLock )
                {
                    if ( instance == null )
                    {
                        instance = new EmailModel ( );
                    }
                }
                return instance;
            }
        }

        #endregion

        public enum EmailType
        {
            Welcome = 1,
            TeamAssignment = 2,
            TeamRemoval = 3,
            WorkAssignment = 4,
            DocumentUpload = 5,
            FormsUserWelcome = 6
        }

        private const string VIEWDISCUSSIONTEXT = "View the discussion and post comments:";

        public void SendNotificationEmail(EmailType type, string recipient, string[] args, User currentUser)
        {
            SendNotificationEmail ( type, string.Empty, recipient, args, currentUser );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sender">An email address that can be replied to for incoming email</param>
        /// <param name="recipient"></param>
        /// <param name="args"></param>
        public void SendNotificationEmail(EmailType type, string sender, string recipient, string[] args, User currentUser)
        {
            string subject = default ( string );
            string body = default ( string );

            switch ( type )
            {
                case EmailType.Welcome:
                    subject = "Welcome to Kiiro";
                    body = GetWelcomeBody ( args );
                    break;
                case EmailType.TeamAssignment:
                    subject = "You have been assigned to a project team in Kiiro";
                    body = GetTeamAssignmentBody ( args );
                    break;
                case EmailType.TeamRemoval:
                    subject = "You have been removed from a project team in Kiiro";
                    body = GetTeamRemovalBody ( args );
                    break;
                case EmailType.WorkAssignment:
                    subject = "You have been assigned work in Kiiro";
                    body = GetWorkItemAssignmentBody ( args );
                    break;
                case EmailType.DocumentUpload:
                    subject = "A new document has been uploaded in Kiiro";
                    body = GetDocumentUploadedBody ( args );
                    break;
                case EmailType.FormsUserWelcome:
                    subject = "Welcome to Kiiro";
                    body = GetFormsUserWelcomeBody ( args );
                    break;
                default:
                    break;
            }
            SendEmail(recipient, subject, body, currentUser);
        }

        /// <summary>
        /// Sends an email to all users that the discussion starter has selected to notify. (discussion.UsersToNotifyEmails)
        /// Users who have selected not to receive email should already be filtered out
        /// </summary>
        /// <param name="discussion"></param>
        public void SendDiscussionCreatedEmail(Discussion discussion, Guid siteCollectionId, string serverRelativeUrl, User currentUser)
        {
            try
            {
                Setup setup;
                User creator;
                using ( SPWeb rootWeb = SPHelpers.GetPortalWeb ( siteCollectionId, serverRelativeUrl ) )
                {
                    setup = SetupModel.GetMidoriSetup ( siteCollectionId, rootWeb.ServerRelativeUrl );
                    creator = UserModel.GetUserById ( discussion.CreatedBy.Id, siteCollectionId, rootWeb.ServerRelativeUrl );
                }

                using ( SPWeb web = SPHelpers.GetWeb ( siteCollectionId, serverRelativeUrl ) )
                {
                    List<User> usersToNotify = UserModel.GetUsersByIds ( discussion.UsersToNotify, siteCollectionId, serverRelativeUrl );

                    foreach ( User user in usersToNotify )
                    {
                        string [ ] args = new string [ ] { discussion.Title, 
                                            FixUrlForUserZone(web.Url + Constants.ProjectFileUrls.DiscussionDisplay + "?ID=" + discussion.Id, user), 
                                            FixUrlForUserZone(web.Url + Constants.ProjectFileUrls.DiscussionsAll, user),
                                            discussion.Text,
                                            discussion.CreatedDate.ToShortDateString(),
                                            creator.FullName,
                                            web.Title };

                        string subject = string.Format ( "New discussion {0}", discussion.Title );
                        string body = GetDiscussionCreatedBody ( setup.AllowEmailReplies, args );

                        SendEmail ( setup, setup.POPEmail, user.Email, subject, body, currentUser );
                    }
                }
            }
            catch ( Exception ex )
            {
                ExceptionManager.HandleException ( ex, false );
            }
        }

        /// <summary>
        /// Sends an email to all participants in a discussion. Filters out users who have selected not to get email notifications
        /// </summary>
        /// <param name="discussion"></param>
        public void SendDiscussionCommentAddedEmail(Discussion discussion, Guid siteCollectionId, string serverRelativeUrl, User currentUser)
        {
            discussion.Comments.Sort ( SPHelpers.CompareByModifiedDate );
            Comment comment = discussion.Comments [ 0 ];
            string rootServerRelativeUrl;
            User commenter;

            using ( SPWeb rootWeb = SPHelpers.GetPortalWeb ( siteCollectionId, serverRelativeUrl ) )
            {
                rootServerRelativeUrl = rootWeb.ServerRelativeUrl;
                commenter = UserModel.GetUserById ( comment.CreatedBy.Id, siteCollectionId, rootServerRelativeUrl );
            }

            using ( SPWeb web = SPHelpers.GetWeb ( siteCollectionId, serverRelativeUrl ) )
            {
                Setup setup = SetupModel.GetMidoriSetup ( siteCollectionId, rootServerRelativeUrl );
                if ( setup != null && setup.SendEmailUpdates )
                {
                    User discussionCreator = UserModel.GetUserById ( discussion.CreatedBy.Id, siteCollectionId, rootServerRelativeUrl );
                    List<int> commentUserIds = new List<int> ( );
                    commentUserIds.Add ( discussionCreator.Id );

                    foreach ( Comment c in discussion.Comments )
                    {
                        if ( !commentUserIds.Contains ( c.CreatedBy.Id ) )
                            commentUserIds.Add ( c.CreatedBy.Id );
                    }

                    if ( commentUserIds.Count > 0 )
                    {
                        List<User> users = UserModel.GetUsersByIds ( commentUserIds, siteCollectionId, serverRelativeUrl );

                        foreach ( User user in users )
                        {
                            string [ ] args = new string [ ] { discussion.Title, 
                                                FixUrlForUserZone(web.Url + Constants.ProjectFileUrls.DiscussionDisplay + "?ID=" + discussion.Id + "#post" + comment.Id, user),
                                                FixUrlForUserZone(web.Url + Constants.ProjectFileUrls.DiscussionsAll, user) };

                            string subject = string.Format ( "Comment added to {0}", discussion.Title );
                            string body = GetDiscussionRepliedToBody ( setup.AllowEmailReplies, args, comment, commenter, siteCollectionId, rootServerRelativeUrl );

                            if ( user.ReceiveEmailNotification )
                                SendEmail ( setup, setup.POPEmail, user.Email, subject, body,currentUser );
                        }
                    }
                }
            }
        }

        public string FixUrlForUserZone ( string url, User user )
        {
            string formsPath = string.Empty;
            string windowsPath = string.Empty;

            using ( SPSite site = new SPSite ( user.SiteCollectionId ) )
            {
                SPWebApplication webApp = site.WebApplication;
                SPAlternateUrl currUrl = webApp.AlternateUrls [ site.Url ];
                foreach ( SPAlternateUrl altUrl in webApp.AlternateUrls )
                {
                    if ( webApp.IisSettings.ContainsKey ( altUrl.UrlZone ) && webApp.IisSettings [ altUrl.UrlZone ] != null )
                    {
                        if ( !string.IsNullOrEmpty ( webApp.IisSettings [ altUrl.UrlZone ].MembershipProvider ) &&
                            webApp.IisSettings [ altUrl.UrlZone ].MembershipProvider == Constants.Permissions.FBAMembershipProviderName )
                            formsPath = altUrl.Uri.ToString ( ).Trim ( '/' );
                        else if ( webApp.IisSettings [ altUrl.UrlZone ].AuthenticationMode == System.Web.Configuration.AuthenticationMode.Windows )
                            windowsPath = altUrl.Uri.ToString ( ).Trim ( '/' );
                    }
                }
            }

            if ( user.IsFormsUser && !url.Contains ( formsPath ) && !string.IsNullOrEmpty ( windowsPath ) )
                url = url.Replace ( windowsPath, formsPath );

            if ( !user.IsFormsUser && url.Contains ( formsPath ) && !string.IsNullOrEmpty ( formsPath ) )
                url = url.Replace ( formsPath, windowsPath );

            return url;
        }

        #region Email Bodies

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = User's name, 1 = Midori url</param>
        /// <returns></returns>
        private string GetWelcomeBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>Hi {0},</p>" );
            sb.Append ( "<p>Welcome to Kiiro.</p>" );
            sb.Append ( "<p>Login to Kiiro here: <a href='{1}'>{1}</a></p>" );

            if ( args.Length >= 2 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = User's name, 1 = Login, 2 = Password, 3 = Midori url</param>
        /// <returns></returns>
        private string GetFormsUserWelcomeBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>Hi {0},</p>" );
            sb.Append ( "<p>Welcome to Kiiro.</p>" );
            sb.Append ( "<p>Login: {1}<br />Password: {2}</p>" );
            sb.Append ( "<p>Login to Kiiro here: <a href='{3}'>{3}</a></p>" );

            if ( args.Length >= 3 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ], args [ 3 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = Project name, 1 = Role, 2 = Project site url</param>
        /// <returns></returns>
        private string GetTeamAssignmentBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>You have been added to a project team in Kiiro.</p>" );
            sb.Append ( "<p>Project: {0}<br />Your role: {1}</p>" );
            sb.Append ( "<p>Go to the project site: <a href=\"{2}\">{2}</a></p>" );

            if ( args.Length >= 2 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = Project name, 1 = midori url</param>
        /// <returns></returns>
        private string GetTeamRemovalBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>You have been removed from a project team in Kiiro.</p>" );
            sb.Append ( "<p>Project: {0}</p>" );
            sb.Append ( "<p>Go to Kiiro: <a href='{1}'>{1}</a></p>" );

            if ( args.Length >= 2 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = workitemtype, 1 = title, 2 = work item url, 3 = project title, 4 = project url</param>
        /// <returns></returns>
        private string GetWorkItemAssignmentBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>You have been assigned work in Kiiro.</p>" );
            sb.Append ( "<p>Project: {3} <a href='{4}'>{4}</a></p>" );
            sb.Append ( "<p>{0} details: {1}</p>" );
            sb.Append ( "<p>Go to the " + args [ 0 ].ToLower ( ) + ": <a href=\"{2}\">{2}</a></p>" );

            if ( args.Length >= 5 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ], args [ 3 ], args [ 4 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = Project title, 1 = Project url, 2 = List of document links</param>
        /// <returns></returns>
        private string GetDocumentUploadedBody ( string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            sb.Append ( "<p>New documents have been uploaded to Kiiro.</p>" );
            sb.Append ( "<p>Project: {0} <a href='{1}'>{1}</a></p>" );
            sb.Append ( "<p>The new documents are listed below:</p>{2}" );

            if ( args.Length >= 3 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ] );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = Title, 1 = Discussion url, 2 = All discussions url, 3 = Discussion text, 4 = Created date, 5 = Created by name, 6 = Project name</param>
        /// <returns></returns>
        private string GetDiscussionCreatedBody ( bool supportReplies, string [ ] args )
        {
            StringBuilder sb = new StringBuilder ( );
            if ( supportReplies )
                sb.Append ( "<hr />Reply above to post a comment to this discussion.<br /><hr />" );
            sb.Append ( "<h3>{0} has been added to the project {6}</h3>" );
            sb.Append ( "<strong>Discussion text: </strong> {3}<br /><br />" );
            sb.Append ( "<strong>Created: </strong> {4} by {5} <hr /><br />" );
            sb.Append ( "{7}<br /><a href=\"{1}\">{1}</a><br /><br />" );
            sb.Append ( "View all discussions for the project:<br /><a href=\"{2}\">{2}</a>" );

            if ( args.Length >= 7 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ], SPHelpers.FormatCommentText ( args [ 3 ] ), args [ 4 ], args [ 5 ], args [ 6 ], VIEWDISCUSSIONTEXT );

            return default ( string );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args">0 = Discussion title, 1 = discussion url (goes to current comment), 2 = all discussions url</param>
        /// <param name="comments"></param>
        /// <returns></returns>
        private string GetDiscussionRepliedToBody ( bool supportReplies, string [ ] args, Comment comment, User commenter, Guid siteCollectionId, string rootServerRelativeUrl )
        {
            StringBuilder sb = new StringBuilder ( );
            if ( supportReplies )
                sb.Append ( "<hr />Reply above to post a comment to this discussion.<br /><hr />" );
            sb.Append ( "<h3>A reply to {0} has been added</h3>" );
            sb.Append ( "<strong>Comment text: </strong>" + SPHelpers.FormatCommentText ( comment.Text ) + "<br /><br />" );
            sb.Append ( "<strong>Added: </strong>" + comment.CreatedDate.ToShortDateString ( ) + " by " + commenter.FullName + "<hr /><br />" );
            sb.Append ( "{3}<br /><a href=\"{1}\">{1}</a><br /><br />" );
            sb.Append ( "To view all discussions for the project go to the following url:<br /><a href=\"{2}\">{2}</a><br /><br />" );

            if ( args.Length >= 3 )
                return string.Format ( sb.ToString ( ), args [ 0 ], args [ 1 ], args [ 2 ], VIEWDISCUSSIONTEXT );

            return default ( string );
        }

        #endregion


        private void SendEmail(string to, string subject, string body, User currentUser)
        {
            if ( SPContext.Current != null && SPContext.Current.Site != null && SPContext.Current.Web != null )
            {
                Guid siteCollectionId = SPContext.Current.Site.ID;
                string serverRelativeUrl = SPContext.Current.Web.ServerRelativeUrl.Length > 1 ? SPContext.Current.Web.ServerRelativeUrl : "";

                Setup setup = SetupModel.GetMidoriSetup ( siteCollectionId, serverRelativeUrl );
                SendEmail ( setup, string.Empty, to, subject, body, currentUser );
            }
        }

        private void SendEmail ( string to, string subject, string body, Guid siteCollectionId, string relativeUrl )
        {
            Setup setup = SetupModel.GetMidoriSetup ( siteCollectionId, relativeUrl );
            SendEmail ( setup, string.Empty, to, subject, body, new User() );
        }

        private void SendEmail(Setup setup, string replyTo, string to, string subject, string body, User currentUser)
        {
            try
            {
                if ( !string.IsNullOrEmpty ( setup.SMTPInfo ) && !string.IsNullOrEmpty ( setup.EmailFromAddress ) && setup.SendEmailUpdates )
                {
                    MailAddress fromInfo = string.IsNullOrEmpty(currentUser.FullName) ? new MailAddress(setup.EmailFromAddress,"Kiiro") : new MailAddress(setup.EmailFromAddress,currentUser.FullName);
                    MailMessage msg = new MailMessage(setup.EmailFromAddress, to, subject, body);
                    msg.From = fromInfo;
                    msg.IsBodyHtml = true;
                    msg.ReplyTo = string.IsNullOrEmpty ( replyTo ) ? null : new MailAddress ( replyTo );

                    SmtpClient mailClient = new SmtpClient ( setup.SMTPInfo );
                    mailClient.Send ( msg );
                }
                else
                {
                    Logging.LoggingManager.LogMessage ( "Email notification error", "Kiiro settings do not contain valid outgoing email settings" );
                }
            }
            catch ( Exception ex )
            {
                string error = string.Format ( "\r\n\r\n Error sending email {0} to {1} Email Body: {2} Error msg: {3}\r\n\r\n\r\n", subject, to, body, ex.Message );
                Logging.LoggingManager.LogMessage ( "Email notification error", error );
            }
        }


        #region Incoming Email

        public void CheckPop3Account ( Guid siteCollectionId, string serverRelativeUrl )
        {
            string host;
            int port;
            List<int> msgsToDelete = new List<int> ( );

            Setup setup = SetupModel.GetKiiroSetupNoCache ( siteCollectionId, serverRelativeUrl );

            if ( setup != null )
            {
                if ( setup.POPInfo != null )
                {
                    if ( setup.POPInfo.IndexOf ( ':' ) > 0 )
                    {
                        host = setup.POPInfo.Substring ( 0, setup.POPInfo.IndexOf ( ':' ) );
                        int.TryParse ( setup.POPInfo.Substring ( setup.POPInfo.IndexOf ( ':' ) + 1 ), out port );
                    }
                    else
                    {
                        host = setup.POPInfo;
                        port = 110;
                    }

                    using ( PopClient popClient = new PopClient ( host, port ) )
                    {
                        try
                        {
                            popClient.UseSSL = true;
                            popClient.Connect ( );
                        }
                        catch
                        {
                            popClient.UseSSL = false;
                            popClient.Connect ( );
                        }

                        popClient.Login ( setup.POPEmail, setup.POPPassword ); // include "recent:" for gmail? eg: recent:midoritestls@gmail.com

                        foreach ( MessageInfo msgInfo in popClient.Messages )
                        {
                            Message m = null;
                            try
                            {
                                m = popClient.GetMessage ( msgInfo.MessageNumber );
                            }
                            catch ( Exception ex )
                            {
                                Logging.LoggingManager.LogMessage ( "Timer job error",
                                    string.Format ( "Error retrieving message {0} \r\n {1}", msgInfo.MessageNumber, ex.Message ) );
                            }

                            if ( m != null )
                            {
                                bool deleteMessage = false;
                                string [ ] parsedMsg;
                                try
                                {
                                    #region Save Comment

                                    string senderEmail = m.From.Substring ( m.From.IndexOf ( "<" ) + 1, m.From.IndexOf ( ">" ) - ( m.From.IndexOf ( "<" ) + 1 ) );
                                    User sender = UserModel.GetUserByEmail ( senderEmail, siteCollectionId, serverRelativeUrl );
                                    if ( sender != null )
                                    {
                                        using ( SPWeb web = SPHelpers.GetWeb ( siteCollectionId, serverRelativeUrl ) )
                                        {
                                            string zoneSafeUrl = FixUrlForUserZone ( web.Url, sender );
                                            parsedMsg = ParseMessage ( m.TextBody, zoneSafeUrl );

                                            if ( parsedMsg [ 3 ] == zoneSafeUrl ) // is the email reply for this Kiiro portal
                                            {
                                                string projectWebUrl = serverRelativeUrl == "/" ? parsedMsg [ 1 ] : serverRelativeUrl + parsedMsg [ 1 ];

                                                string fullLogin = ( sender.IsFormsUser ? Constants.Permissions.FBA + ":" : "" ) + sender.Login;
                                                sender.Groups = SPHelpers.GetUserGroups ( fullLogin, siteCollectionId, projectWebUrl );

                                                Comment comment = new Comment ( );
                                                comment.EditType = EditType.Created;
                                                comment.CreatedDate = DateTime.Now;
                                                comment.ModifiedDate = DateTime.Now;
                                                comment.CreatedBy = sender;
                                                comment.ModifiedBy = sender;
                                                comment.Text = parsedMsg [ 0 ];
                                                comment.DiscussionId = Convert.ToInt32 ( parsedMsg [ 2 ] );

                                                CommentModel.Save ( comment, siteCollectionId, projectWebUrl );

                                                deleteMessage = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Logging.LoggingManager.LogMessage ( "Incoming email error - Message number: ", "\r\n\r\nNo user with the email '" + senderEmail + "' could be found" );
                                    }
                                    #endregion
                                }
                                catch ( Exception ex )
                                {
                                    Logging.LoggingManager.LogMessage ( "Incoming email error - Message number: ", "\r\n\r\n" + m.TextBody + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n\r\n\r\n" );
                                }

                                if ( deleteMessage )
                                    msgsToDelete.Add ( msgInfo.MessageNumber );
                            }
                        }

                        popClient.RSET ( );
                        foreach ( int i in msgsToDelete )
                        {
                            popClient.DeleteMessage ( i );
                        }
                        popClient.QUIT ( );
                    }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg"></param>
        /// <returns>string array 0 = reply text, 1 = web url, 2 = discussion id, 3 = message site url</returns>
        private string [ ] ParseMessage ( string msg, string siteUrl )
        {
            string [ ] parsedMsg = null;

            string reply = GetReply ( msg );
            string webUrl = string.Empty;
            string discussionId = string.Empty;
            string msgSiteUrl = string.Empty;

            if ( msg.IndexOf ( VIEWDISCUSSIONTEXT ) > 0 && msg.IndexOf ( siteUrl ) > 0 )
            {
                int linkStart = msg.IndexOf ( siteUrl, msg.IndexOf ( VIEWDISCUSSIONTEXT ) );
                string discussionUrl = msg.Substring ( linkStart, msg.IndexOf ( "\r\n", linkStart ) - linkStart ).Trim ( );
                webUrl = discussionUrl.Substring ( siteUrl.Length + 1 );
                webUrl = "/" + webUrl.Substring ( 0, webUrl.IndexOf ( "/" ) );
                msgSiteUrl = discussionUrl.Remove ( discussionUrl.LastIndexOf ( "/" ) );
                msgSiteUrl = msgSiteUrl.Remove ( msgSiteUrl.LastIndexOf ( "/" ) );
                discussionId = discussionUrl.ToLower ( ).Substring ( discussionUrl.ToLower ( ).IndexOf ( "id=" ) + 3 );
                if ( discussionId.Contains ( "#" ) )
                    discussionId = discussionId.Remove ( discussionId.IndexOf ( "#" ) );
            }

            if ( string.IsNullOrEmpty ( reply ) || string.IsNullOrEmpty ( webUrl ) || string.IsNullOrEmpty ( discussionId ) )
                throw new Exception ( "Email is not properly formatted." );

            parsedMsg = new string [ ] { reply, webUrl, discussionId, msgSiteUrl };
            return parsedMsg;
        }

        private string GetReply ( string msg )
        {
            string reply = string.Empty;

            if ( msg.IndexOf ( "Reply above to post a comment to this discussion" ) > 0 )
            {
                reply = msg.Substring ( 0, msg.IndexOf ( "Reply above to post a comment to this discussion" ) );
                reply = RemoveBreakline ( reply );

                while ( reply.StartsWith ( "\r\n" ) )
                    reply = reply.Substring ( 4 );

                while ( reply.EndsWith ( "\r\n" ) )
                    reply = reply.Substring ( 0, reply.Length - 4 );
            }

            return reply;
        }

        private string RemoveBreakline ( string text )
        {
            // parse out breaklines from outlook & hotmail
            Regex r = new Regex ( @"From:.*\r\nSent:.*\r\nTo:.*\r\nSubject:.*" );
            string [ ] textSplit = r.Split ( text );
            if ( textSplit.Length > 1 )
                return text.Substring ( 0, textSplit [ 0 ].Length );

            // parse out breaklines from gmail
            r = new Regex ( @"On .* at .* wrote:\r\n\r\n>" );
            textSplit = r.Split ( text );
            if ( textSplit.Length > 1 )
                return text.Substring ( 0, textSplit [ 0 ].Length );

            return text.Substring ( 0, text.Length - 1 );
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.Model/EmailModel.cs $
 * 
 * 21    2/08/10 5:04p Camerons
 * 
 * 20    1/25/10 1:17p Camerons
 * 
 * 19    1/12/10 12:03p Camerons
 * 
 * 18    26/11/09 10:35a Camerons
 * 
 * 17    26/11/09 10:02a Camerons
 * 
 * 16    17/11/09 6:46p Camerons
 * 
 * 15    30/10/09 1:33p Camerons
 * 
 * 14    30/10/09 12:54p Camerons
 * 
 * 13    30/09/09 9:32a Shafia
 * 
 * 12    22/09/09 6:03p Camerons
 * Code changes to support creating user on demand - version 1.1.x.x
 * 
 * 11    8/09/09 5:09p Camerons
 * Added check for null setup in CheckPop3Account()
 * 
 * 10    4/09/09 3:18p Camerons
 * 
 * 9     17/08/09 10:29a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/